import hashlib

from werkzeug.datastructures import FileStorage
import os
from configs import BaseConfig


def save_avatar(file: FileStorage):
    # picture name
    name = file.filename
    # picture content
    content = file.stream.read()
    new_name = hashlib.md5(content).hexdigest() + '.' + name.split('.')[-1]

    file_path = os.path.join(BaseConfig.ROOT_PATH, 'static', 'upload', 'avatar', new_name)

    with open(file_path, 'wb') as file:
        file.write(content)

    url = '/'.join(['static', 'upload', 'avatar', new_name])
    return '/' + url


def save_article_index_image(file: FileStorage):
    # picture name
    name = file.filename
    # picture content
    content = file.stream.read()
    new_name = hashlib.md5(content).hexdigest() + '.' + name.split('.')[-1]

    file_path = os.path.join(BaseConfig.ROOT_PATH, 'static', 'upload', 'article_index_image', new_name)

    with open(file_path, 'wb') as file:
        file.write(content)

    url = '/'.join(['static', 'upload', 'article_index_image', new_name])
    return '/' + url


def save_article_content_image(file: FileStorage):
    # picture name
    name = file.filename
    # picture content
    content = file.stream.read()

    new_name = hashlib.md5(content).hexdigest() + '.' + name.split('.')[-1]

    file_path = os.path.join(BaseConfig.ROOT_PATH, 'static', 'upload', 'article_content_image', new_name)

    with open(file_path, 'wb') as file:
        file.write(content)

    url = '/'.join(['static', 'upload', 'article_content_image', new_name])
    return '/' + url